using System;
using AppSpaces.Transport.Sockets.Auth.Common;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;
using System.Net;
using Windows.Networking;
using Windows.Networking.Sockets;

namespace XcoAppSpaces.Transport.Sockets.Auth
{
	//TODO implement a blacklist with global connections to other ports
	class CheckIpBlacklist : ICheckIpBlacklist
	{
        private readonly ListOfExpiringIPAddressEntries localBlacklist;

		public CheckIpBlacklist(int entryLifetimeSeconds, int timerInterval)
		{
            localBlacklist = new ListOfExpiringIPAddressEntries(entryLifetimeSeconds, timerInterval);
		}

		public CheckIpBlacklist() : this(3600, 60000)
		{
		}

		public void In_InvalidAddress(HostName address)
		{
			//Console.WriteLine("CheckIpBlacklist.In_InvalidAddress");
			localBlacklist.GetOrAdd(address);
		}

		public void In_Connection(StreamSocket tcpClient)
		{
			//Console.WriteLine("CheckIpBlacklist.In_Connection");
			if (localBlacklist.Contains(tcpClient.Information.RemoteHostName))
				Out_BlockedConnection(tcpClient);
			else
				Out_AllowedConnection(tcpClient);
		}

		public event TcpClientHandler Out_AllowedConnection;

        public event TcpClientHandler Out_BlockedConnection;

		public void Dispose()
		{
			if (localBlacklist != null)
				localBlacklist.Dispose();
		}
	}
}